<?php

/**
 * Albireo Kernel
 *
 * @copyright  Copyright (c) 2010 Albireo Solutions
 * @package    Kernel
 */

namespace KernelModule;

use Nette\Object;
use Nette\Security\AuthenticationException;
use Nette\Security\Identity;
use Nette\Security\Iauthenticator;

use Albireo\AlbireoPassword;

use Celebrio\AccessControl\AclConstants;
use Celebrio\PasswordHasher;

use \InvalidArgumentException;

/**
 * Masteruser authenticator.
 *
 * @author     Albireo Solutions
 * @package    Kernel
 */
class KernelMasterAuthenticator extends Object implements IAuthenticator {

    /**
     * Performs an authentication for the ROOT_USER.
     *
     * @param  array $credentials sign in credentials
     * @return IIdentity
     * @throws AuthenticationException
     */
    public function authenticate(array $credentials) {
        if ($credentials[self::USERNAME] !== AclConstants::ROOT_USER) {
            throw new AuthenticationException(_("Only root can sign in to the critical mode."));
        }
        if (strcasecmp(AlbireoPassword::PASSWORD, hash('sha1', $credentials[self::PASSWORD])) === 0) {
//            $identity = $credentials["extra"];
//            if ($identity != null) {
//                $roles = $identity->getRoles();
//            } else {
//                $roles = array();
//            }

//            if (in_array("admin", $roles)) {
//                throw new \Exception("Master root is not supported (not tested yet).");
//                //TODO: array of user information, what to remember
//                $row = array (
//                        "password" => $identity->password
//                );
//                $roles[] = "masteradmindb";
//                return new Identity($identity->getName(), $roles, $row);
//            } else {
                $data[self::PASSWORD] = PasswordHasher::userHash(
                        $credentials[self::USERNAME],
                        $credentials[self::PASSWORD]);
                return new Identity(AclConstants::ROOT_USER, array(AclConstants::ROOT_ROLE), $data);
//            }
        }
        throw new AuthenticationException(_("Invalid password."), self::INVALID_CREDENTIAL);
    }

}